import Vue from 'vue';
import httpApi from '@/common/http.api.js';
import * as API from '@/config/api.js'
import amap from './amap-wx.130.js'
// 余额支付
async function payment(target_id, target_type, pay_type, total_amount, trade_pwd, client) {
	return new Promise(async (reslove, reject) => {
		let params = {
			target_id: target_id,
			target_type: target_type,
			pay_type: pay_type,
			total_amount: total_amount,
			trade_pwd: trade_pwd,
			client: client
		}
		let res = await uni.$u.api.pay(params)
		if (res.code == 1) {
			reslove(res)
		} else {
			reject(res)
		}
	})
}

// 易支付
async function easyPay(params, provider) {
	uni.showLoading({
		title: '加载中...',
		mask: true
	})
	return new Promise(async (resolve, reject) => {
		API.pay2(params, res => {
			// 根据平台不同处理支付跳转
			// #ifdef H5
			window.location.href = res.data.data.pay_info;
			// #endif

			// #ifdef APP-PLUS
			// plus.runtime.openURL(res.data.data.pay_info);
			uni.navigateTo({
				url: '/pages/webview/webview?url=' + encodeURIComponent(res.data.data.pay_info)
			});
			// #endif

			// #ifdef MP-WEIXIN || MP-ALIPAY
			uni.navigateTo({
				url: '/pages/webview/webview?url=' + encodeURIComponent(res.data.data.pay_info)
			});
			// #endif
		})
	})
}
// App微信支付宝支付
async function wxPay(params, provider) {
	return new Promise(async (resolve, reject) => {
		API.pay(params, res => {
			if (res.data.code == 1) {
				uni.requestPayment({
					provider: provider == 'wechat' ? 'wxpay' : 'alipay',
					orderInfo: provider == 'wechat' ? res.data.data : res.data.data,
					success: (suc) => {
						resolve(res); //返回写函数里面你要执行的内容
					},
					fail: (f) => {
						console.log(f)
						reject(f)
					},
				});
			}
		})

	})
}

// App微信支付宝支付
async function wxPay2(params, provider) {
	return new Promise(async (resolve, reject) => {
		API.pay2(params, res => {
			// console.log(res.data.data)
			if (res.data.code == 1) {
				// #ifdef H5

				resolve(res.data.data)
				return
				// #endif
				uni.requestPayment({
					provider: provider == 'wechat' ? 'wxpay' : 'alipay',
					orderInfo: provider == 'wechat' ? res.data.data : res.data.data,
					success: (suc) => {
						resolve(res); //返回写函数里面你要执行的内容
					},
					fail: (f) => {
						console.log(f)
						reject(f)
					},
				});
			}
		})

	})
}
// 微信支付
async function weChatPay(params, provider) {
	return new Promise(async (resolve, reject) => {
		API.pay(params, res => {
			let payParams = res.data.data
			if (res.data.code == 1) {
				uni.requestPayment({
					timeStamp: payParams.timeStamp,
					nonceStr: payParams.nonceStr,
					package: payParams.package,
					signType: payParams.signType,
					paySign: payParams.paySign,
					success: (s) => {
						resolve(res); //返回写函数里面你要执行的内容
					},
					fail: (f) => {
						reject(f)
					}
				});
			}
		})


	})
}


async function aliPay2(params, provider) {
	return new Promise(async (resolve, reject) => {
		API.pay2(params, res => {
			let trade_no = res.data.data.trade_no
			uni.requestPayment({
				provider: 'alipay',
				orderInfo: trade_no.toString(), //微信、支付宝订单数据 【注意微信的订单信息，键值应该全部是小写，不能采用驼峰命名】
				success: function (s) {
					resolve(res); //返回写函数里面你要执行的内容
				},
				fail: function (f) {
					reject(f)
				}
			});
		})
	})
}

async function aliPay(params, provider) {
	return new Promise(async (resolve, reject) => {
		API.pay(params, res => {

			if (res.data.code == 1) {
				let trade_no = res.data.data.trade_no

				uni.requestPayment({
					provider: 'alipay',
					orderInfo: trade_no.toString(), //微信、支付宝订单数据 【注意微信的订单信息，键值应该全部是小写，不能采用驼峰命名】
					success: function (s) {
						resolve(res); //返回写函数里面你要执行的内容
					},
					fail: function (f) {
						reject(f)
					}
				});

			}
		})


	})
}


// 微信支付
async function weChatPay2(params, provider) {
	return new Promise(async (resolve, reject) => {
		API.pay2(params, res => {
			let payParams = res.data.data
			if (res.data.code == 1) {
				uni.requestPayment({
					timeStamp: payParams.timeStamp,
					nonceStr: payParams.nonceStr,
					package: payParams.package,
					signType: payParams.signType,
					paySign: payParams.paySign,
					success: (s) => {
						resolve(res); //返回写函数里面你要执行的内容
					},
					fail: (f) => {
						reject(f)
					}
				});
			}
		})


	})
}


// 微信公众号支付
async function h5WxPay(params) {
	return new Promise(async (resolve, reject) => {
		let res = await uni.$u.api.order_pay(params)
		let info = res.data.payParams;
		if (res.code == 1) {
			WeixinJSBridge.invoke('getBrandWCPayRequest', {
				debug: false,
				"appId": info.appId, //公众号名称，由商户传入
				"timeStamp": info.timeStamp, //时间戳，自1970年以来的秒数
				"nonceStr": info.nonceStr, //随机串
				"package": info.package,
				"signType": info.signType, //微信签名方式：
				"paySign": info.paySign //微信签名
			},
				(data) => {
					if (data.err_msg == "get_brand_wcpay_request:ok") {
						resolve(data); //返回写函数里面你要执行的内容
					}
					reject(data)
				})
		}
	})
}
// 根据选中的checked以逗号形式拼接字符串
async function jobData(params, val) {
	return new Promise(async (resolve, reject) => {
		var result = ''
		if (params.length > 0) {
			params.forEach((p) => {
				if (p.checked) {
					result += p[val] + ','
				}
			})
			result = result.substring(0, result.length - 1)
			resolve(result)
		} else {
			resolve('')
		}
	})
}
// 处理多张图片以逗号形式拼接字符串
async function imgData(params) {
	return new Promise(async (resolve, reject) => {
		var result = ''
		if (params.length > 0) {
			params.forEach((p) => {
				result += p.value + ','
			})
			result = result.substring(0, result.length - 1)
			resolve(result)
		} else {
			resolve('')
		}
	})
}
// App定位
async function getLocation() {
	return new Promise(async (resolve, reject) => {
		uni.getLocation({
			type: 'gcj02',
			geocode: true,
			success: (res) => {
				resolve(res)
			},
			fail: (f) => {
				console.log(f)
				reject(f)
			}
		});
	})
}
// 微信小程序定位
async function wxLocation() {
	return new Promise(async (resolve, reject) => {
		var amapPlugin = new amap.AMapWX({
			key: getApp().globalData.AMapWX
		})
		await amapPlugin.getRegeo({
			success: (data) => {
				resolve(data[0])
			},
			fail: (f) => {
				reject(f)
			}
		})
	})
}
// 获取星期
function severalWeeks() {
	return new Promise((resolve, reject) => {
		var now = new Date();
		var day = now.getDay();
		var weeks = new Array("星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六");
		var week = weeks[day];
		resolve(week)
	})
}
// 数组转字符串逗号拼接
async function arrData(params, name) {
	console.log(params)
	return new Promise(async (resolve, reject) => {
		var result = ''
		if (params.length > 0) {
			await params.forEach((p) => {
				result += p[name] + ','
			})
			result = result.substring(0, result.length - 1)
			await resolve(result)
		} else {
			await resolve('')
		}
	})
}
// 查看图片
function previewImg(current, urls) {
	uni.previewImage({
		current,
		urls
	})
}

// 拨打电话
function makePhoneCall(phone) {
	uni.makePhoneCall({
		phoneNumber: phone //仅为示例
	});
}

// 去导航
function openLocation(name, latitude, longitude) {
	uni.openLocation({
		name,
		latitude,
		longitude,
		success: (s) => {
			console.log(s)
		},
		fail: (f) => {
			console.log(f)
		}
	})
}
// 复制
function setClipboardData(value) {
	uni.setClipboardData({
		data: value,
		success: (res) => {
			uni.showToast({
				title: "复制成功",
			});
		},
	});
}
// APP分享微信
function appShare(regcode) {
	uni.share({
		provider: "weixin", //分享服务提供商（即weixin|qq|sinaweibo）
		scene: 'WXSceneSession', //场景，可取值参考下面说明。
		type: 0, //分享形式
		href: `${api.apiUrl.split('index.php')[0]}/h5/#/pages/login/register?regcode=${regcode}`, //跳转链接
		title: getApp().globalData.title, //分享内容的标题
		summary: getApp().globalData.summary, //分享内容的摘要
		imageUrl: `${api.apiUrl.split('index.php')[0]}/h5/logo.png`, //图片地址
		success: (res) => {
		},
		fail: (err) => {
		}
	});
}

function timeList() {
	let arr = []
	let newArr = []
	let result = Array.from(new Array(2), () => new Array(24))
	for (var i = 0; i < 24; i++) {
		arr.push({
			'value': i >= 10 ? '' + i + ':00' : '0' + i + ':00',
			'label': i >= 10 ? '' + i + ':00' : '0' + i + ':00'
		})
	}
	result[0] = arr
	result[1] = arr
	return result
}

function getHour(s1, s2) {
	var reDate = /\d{4}-\d{1,2}-\d{1,2} /;
	s1 = new Date((reDate.test(s1) ? s1 : '2018-1-1 ' + s1).replace(/-/g, '/'));
	s2 = new Date((reDate.test(s2) ? s2 : '2018-1-1 ' + s2).replace(/-/g, '/'));
	var ms = s2.getTime() - s1.getTime();
	if (ms < 0) return 0;
	return Math.floor(ms / 1000 / 60 / 60); //小时
}

function saveImage(img) {
	// #ifdef APP-PLUS
	uni.downloadFile({
		url: img,
		success: (res) => {
			if (res.statusCode === 200) {
				uni.saveImageToPhotosAlbum({
					filePath: res.tempFilePath,
					success: function () {
						uni.showToast({
							title: "保存成功",
							icon: "none"
						});
					},
					fail: function () {
						uni.showToast({
							title: "保存失败，请稍后重试",
							icon: "none"
						});
					}
				});
			}
		}
	});
	// #endif
}
export default {
	payment,
	wxPay,
	wxPay2,
	easyPay,
	weChatPay,
	aliPay,
	weChatPay2,
	aliPay2,
	h5WxPay,
	jobData,
	imgData,
	severalWeeks,
	getLocation,
	wxLocation,
	arrData,
	previewImg,
	makePhoneCall,
	openLocation,
	appShare,
	setClipboardData,
	timeList,
	getHour,
	saveImage
}
